import pandas as pd
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt
from sklearn.metrics import silhouette_score

class CluterUtils(object):
    def __init__(self):
        self.df = pd.read_csv('scenic_data.csv')
        
    def get_k(self):
        features = self.df[['non_weekend_ratio','eldery_ratio','out_province_ratio']]
        # 数据标准化
        scaler = StandardScaler()
        features_scaled = scaler.fit_transform(features)
        
        # 确定最佳聚类数
        silhouette_scores = []
        for k in range(2, 11):
            kmeans = KMeans(n_clusters=k, random_state=42)
            cluster_labels = kmeans.fit_predict(features_scaled)
            silhouette_avg = silhouette_score(features_scaled, cluster_labels)
            silhouette_scores.append(silhouette_avg)
        # 绘制轮廓系数图
        plt.plot(range(2, 11), silhouette_scores, marker='o')
        plt.title('Silhouette Method for Optimal k')
        plt.xlabel('Number of clusters (k)')
        plt.ylabel('Silhouette Score')
        plt.show()
        
if __name__ == "__main__":
    cu = CluterUtils()
    cu.get_k()